import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import Drawer from '@/components/drawer/Index'
import FilterRender from '@/render/FilterRender'
import renderModal, {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import type {
    PeriodInsuranceMaterialsDto,
    InsuranceMaterialsFileDto,
    LongInsuranceCaseListDto,
    ReportCaseResultDto
} from '@/api/insurance/period/types'
import {
    addPeriodInsuranceMaterials,
    removePeriodInsuranceMaterials,
    exportPeriodInsuranceMaterials,
    addDailyInsuranceMaterials,
    removeDailyInsuranceMaterials,
    exportDailyInsuranceMaterials
} from '@/api/insurance/period/index'
import { wait, downloadBlobString } from '@/utils/util'
import { Button, Image, message } from 'ant-design-vue'
import type { TimelineDto } from '@/components/time-line/Index'
import TimelineComponent from '@/components/time-line/Index'
import useUserStore from '@/stores/user'
import Upload, { type UploadFileDto } from '@/components/file/Upload'
import ImageDelete from '@/components/image-delete/Index'
import { max } from 'lodash'

@Component
export class SetMaterialPopView extends FilterRender {
    uploadChangeKey = ''
    @Prop() show!: boolean
    @Prop() previewList!: PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>[]
    @Prop() type!: string
    @Prop() basicInfo!: LongInsuranceCaseListDto<ReportCaseResultDto>
    showDrawer = false

    timelineData = [] as TimelineDto[]

    uploadValue = [] as UploadFileDto[]

    @Emit('update:show')
    updateShow(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Emit('change')
    handleChange() {
        return
    }

    @Watch('show', { immediate: true })
    handleWatchShow() {
        this.showDrawer = this.show
    }

    @Watch('showDrawer', { immediate: true })
    handleWatchShowDialog() {
        this.updateShow(this.showDrawer)
    }

    @Watch('previewList', { immediate: true, deep: true })
    handleWatchPreviewList(newData: PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>[]) {
        if (!newData?.length) {
            this.timelineData = []
            return
        }
        this.timelineData = []
        newData.forEach((item) => {
            this.timelineData.push({
                title: (
                    <div class="flex items-center">
                        <div class="">
                            {item.name}（{item.files?.length ?? 0}/{item.limitSize}）
                        </div>
                        <span class="text-error">*</span>
                        <span class="text-black-200">{item.detail}</span>
                    </div>
                ),
                button: useUserStore().hasPermission('period-insur:report-case-bccl:insert') ? (
                    <>
                        <Upload
                            v-model={this.uploadValue}
                            multiple={false}
                            onChange={(fileList: UploadFileDto[]) =>
                                this.onFileChange(fileList, item)
                            }
                            params={{
                                autoUpload: false,
                                limit: item.limitSize,
                                accept: '.png,.jpg,.jpeg',
                                hideListType: true,
                                exit: item.files.length,
                                maxSize: 5 * 1024 * 1024,
                            }}
                            v-slots={{
                                default: () => {
                                    return <Button>上传材料</Button>
                                }
                            }}
                        ></Upload>
                    </>
                ) : (
                    <></>
                ),
                content: (
                    <div>
                        {item.files?.length ? (
                            <div class="flex gap-12px p-16px">
                                {item.files?.map((i) => {
                                    return (
                                        <ImageDelete
                                            height={60}
                                            width={60}
                                            class="rounded-sm"
                                            src={i.fileUrl}
                                            onRemove={() => this.onDelete(i.fileId)}
                                        ></ImageDelete>
                                    )
                                })}
                            </div>
                        ) : null}
                    </div>
                )
            })
        })
    }

    async onFileChange(
        fileList: UploadFileDto[],
        item: PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>
    ) {
        if (!fileList.length) return
        const query = {
            companyId: this.basicInfo.companyId,
            categoryType: item.type,
            file: fileList[0].base64 as string,
            reportCaseId: Number(this.basicInfo.id)
        }
        if (this.type === 'period') {
            await addPeriodInsuranceMaterials(query)
        } else {
            await addDailyInsuranceMaterials(query)
        }
        this.handleRefresh()
    }

    async onDelete(fileId: number) {
        if (this.type === 'period') {
            await removePeriodInsuranceMaterials(fileId)
        } else {
            await removeDailyInsuranceMaterials(fileId)
        }
        message.success('删除成功')
        this.handleRefresh()
    }

    // 导出材料
    async onExportInsuranceMaterials() {
        if (this.type === 'period') {
            const result = await exportPeriodInsuranceMaterials({
                reportCaseId: Number(this.basicInfo.id),
                insureCompany: this.basicInfo.insurCompany
            })
            await downloadBlobString(result, '长期保保险材料', 'zip')
        } else {
            const result = await exportDailyInsuranceMaterials({
                reportCaseId: Number(this.basicInfo.id),
                insureCompany: this.basicInfo.insureCompanyType
            })
            await downloadBlobString(result, '日保保险材料', 'zip')
        }
    }

    render() {
        return (
            <>
                {this.timelineData.length ? (
                    <TimelineComponent timelineData={this.timelineData} />
                ) : (
                    <div>保司材料类目未配置,请联系管理员</div>
                )}
                {/* {this.renderFilter()} */}
                {/* Drawer 组件暂时不可用 */}
                {/* <Drawer v-model:show={this.showDrawer} title="上传资料" size="700" height="100%">
                    <div>
                        { this.basicForm.element() }
                    </div>
                    <div class="w-full flex items-center justify-center">
                        <Button type="primary" onClick={this.onExportInsuranceMaterials}>导出</Button>
                    </div>
                </Drawer> */}
            </>
        )
    }
}

export default toNative<
    {
        previewList: PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>[]
        type: string
        basicInfo: LongInsuranceCaseListDto<ReportCaseResultDto>
    },
    { change: () => void; refresh: () => void }
        >(SetMaterialPopView)
